package kr.redmist.myfavtwit;

import android.content.Context;
import android.content.SharedPreferences;

import twitter4j.Twitter;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;

/**
 * 트위터 관련 헬퍼 함수.
 * http://qiita.com/gabu/items/f6f39900fd5e449045f9 의 코드를 가져다 씀.
 * Created by Minhyung on 2015-03-06.
 */
public class TwitterUtils {

    private static final String CONSUMER_KEY = "";
    private static final String CONSUMER_SECRET = "";

    private static final String PREF_NAME = "twitter_access_token";
    private static final String TOKEN = "token";
    private static final String TOKEN_SECRET = "token_secret";

    /**
     * Twitter 인스턴스를 취득.
     * @param context
     * @return
     */
    public static Twitter getTwitterInstance(Context context) {
        TwitterFactory factory = new TwitterFactory();
        Twitter twitter = factory.getInstance();
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        AccessToken accessToken = loadAccessToken(context);
        if (accessToken != null) {
            twitter.setOAuthAccessToken(accessToken);
        }
        return twitter;
    }

    /**
     * 액세스 토큰 정보를 프리퍼런스에 보존
     *
     * @param context
     * @param accessToken
     */
    public static void storeAccessToken(Context context, AccessToken accessToken) {
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(TOKEN, accessToken.getToken());
        editor.putString(TOKEN_SECRET, accessToken.getTokenSecret());
        editor.commit();
    }

    /**
     * 액세스 토큰 정보를 프리퍼런스에서 불러들임
     *
     * @param context
     * @return
     */
    public static AccessToken loadAccessToken(Context context) {
        AccessToken accessToken = null;
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        String token = preferences.getString(TOKEN, null);
        String tokenSecret = preferences.getString(TOKEN_SECRET, null);
        if (token != null && tokenSecret != null) {
            accessToken = new AccessToken(token, tokenSecret);
        }
        return accessToken;
    }

    /**
     * 액세스 토큰 정보를 프리퍼런스에서 제거
     *
     * @param context
     */
    public static void clearAccessToken(Context context) {
        SharedPreferences preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.clear();
        editor.commit();
    }

    /**
     *
     *
     * @param context
     * @return
     */
    public static boolean hasAccessToken(Context context) {
        return loadAccessToken(context) != null;
    }

}
